package com.ahui.test;

import com.ahui.handler.FileHandler;
import com.ahui.handler.FileHandlerFactory;
import com.ahui.util.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

/**
 * @author : ph.li
 * @date : 2023/8/26 10:00
 */
@SpringBootTest
@ExtendWith(SpringExtension.class)
@Slf4j
public class Demo {

    @Resource(name = "aHuiThreadPoolExecutor")
    Executor executor;


    // 多线程指定文件夹下的tiff转换为img
    @Test
    public void testTiff2Img() {
        String inputPath = "E:\\文档\\工作\\致宇\\兴证全球\\测试数据\\电子传真2";
        String outputPath = "E:\\文档\\工作\\致宇\\兴证全球\\数据处理\\20230727本人错误、正确统计数据\\jpg";

        // 根据路径读取该路径下的所有文件
        List<File> fileList = FileUtil.getFiles(inputPath);
        CountDownLatch countDownLatch = new CountDownLatch(fileList.size());
        CopyOnWriteArrayList<Exception> errors = new CopyOnWriteArrayList<>();
        // 循环处理tif文件
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < fileList.size(); i++) {
            log.info("=================开始处理第{}个文件：{}===================", (i + 1));
            final int idx = i;
            executor.execute(() -> {
                try {
                    // 本地通用转化测试
//                    TifUtil.tif2img(fileList.get(idx), outputPath, "jpg");
                    // 公司转A4测试
                     TifUtil.tiff2Img1(fileList.get(idx),outputPath);
                } catch (Exception e) {
                    errors.add(e);
                } finally {
                    countDownLatch.countDown();
                    log.info("================= 文件处理 countDownLatch 计数减一，值为 : {} ===================", countDownLatch.getCount());
                }
            });

        }
        try {
            countDownLatch.await();
        } catch (Exception e) {
            log.error("线程执行时发生中断异常" + e);
        }
        log.info("================= countDownLatch 结束等待，值为 : {} ===================", countDownLatch.getCount());
        if (!errors.isEmpty()) {
            log.error("文件处理存在错误: {}", errors);
        }

        long endTime = System.currentTimeMillis();
        System.out.println("共耗时：" + ((endTime - startTime) / 1000.0) + "秒");  //转化用时
    }

    // 多线程word转pdf
    @Test
    public void word2pdf() {
        String inputPath = "E:\\文档\\工作\\致宇\\兴证全球\\数据处理\\8.29非公开定增样本\\word";
        String outputPath = "E:\\文档\\工作\\致宇\\兴证全球\\数据处理\\8.29非公开定增样本\\pdf";

        // 根据路径读取该路径下的所有文件
        List<File> fileList = FileUtil.getFiles(inputPath);
        CountDownLatch countDownLatch = new CountDownLatch(fileList.size());
        CopyOnWriteArrayList<Exception> errors = new CopyOnWriteArrayList<>();
        // 循环处理word文件
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < fileList.size(); i++) {

            File currentFile = fileList.get(i);
            // 创建文件夹 tempPdfPath
            //  + File.separator + FileUtil.getFileNameNoExtName(fileList.get(i).getAbsolutePath())
            String tempPdfFolder = outputPath;
            Path tempPdfFolderPath = Paths.get(tempPdfFolder);
            if (!Files.exists(tempPdfFolderPath) && !Files.isDirectory(tempPdfFolderPath)) {
                try {
                    Files.createDirectories(tempPdfFolderPath);
                } catch (IOException e) {
                    log.error("生成临时文件夹失败");
                }
            }

            String pdfPath = tempPdfFolder + File.separator +FileUtil.RemoveFileSuffix(currentFile.getName()) + ".pdf";

            log.info("=================开始处理第{}个文件：{}===================", (i + 1));
            final int idx = i;
            executor.execute(() -> {
                try {
                    // 本地通用转化测试
                    WordUtil.wordToPdf(currentFile.getAbsolutePath(), pdfPath);
//                    WordUtil.word2Pdf(fileList.get(idx),pdfPath);
//                    TifUtil.tif2img(fileList.get(idx), outputPath, "jpg");
                    // 公司转A4测试
//                     TifUtil.tiff2Img1(currentFile,outputPath);
                } catch (Exception e) {
                    errors.add(e);
                } finally {
                    countDownLatch.countDown();
                    log.info("================= 文件处理 countDownLatch 计数减一，值为 : {} ===================", countDownLatch.getCount());
                }
            });

        }
        try {
            countDownLatch.await();
        } catch (Exception e) {
            log.error("线程执行时发生中断异常" + e);
        }
        log.info("================= countDownLatch 结束等待，值为 : {} ===================", countDownLatch.getCount());
        if (!errors.isEmpty()) {
            log.error("文件处理存在错误: {}", errors);
        }

        long endTime = System.currentTimeMillis();
        System.out.println("共耗时：" + ((endTime - startTime) / 1000.0) + "秒");  //转化用时
    }

    // 单线程word转pdf
    @Test
    public void word2pdf2() {
        String inputPath = "E:\\文档\\工作\\致宇\\兴证全球\\数据处理\\8.29非公开定增样本\\word";
        String outputPath = "E:\\文档\\工作\\致宇\\兴证全球\\数据处理\\8.29非公开定增样本\\pdf";
        List<File> files = FileUtil.getFiles(inputPath);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < files.size(); i++) {
            File currentFile = files.get(i);
            // 创建文件夹 tempPdfPath
            //  + File.separator + FileUtil.getFileNameNoExtName(fileList.get(i).getAbsolutePath())
            String tempPdfFolder = outputPath;
            Path tempPdfFolderPath = Paths.get(tempPdfFolder);
            if (!Files.exists(tempPdfFolderPath) && !Files.isDirectory(tempPdfFolderPath)) {
                try {
                    Files.createDirectories(tempPdfFolderPath);
                } catch (IOException e) {
                    log.error("生成临时文件夹失败");
                }
            }

            String pdfPath = tempPdfFolder + File.separator +FileUtil.RemoveFileSuffix(currentFile.getName()) + ".pdf";
            if (!FileUtil.isWordFile(currentFile)) {
                continue;
            }
            WordUtil.wordToPdf(currentFile.getAbsolutePath(), pdfPath);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("共耗时：" + ((endTime - startTime) / 1000.0) + "秒");  //转化用时
    }


    /**
     * inputPath ： 输入文件夹路径
     * outputPath ： 输出文件夹路径
     * 作用： 将pdf、word、tiff文件转换为img，输出到指定路径，并将所有图片路径保存到集合中
     * */
    @Test
    public void fileHandler(){
        String inputPath = "E:\\文档\\工作\\文件测试\\run-file";
        String outputPath = "E:\\文档\\工作\\文件测试\\run-imag";
        List<String> imgPathList = new ArrayList<>();
        // 根据路径读取该路径下的所有文件
        List<File> files = FileUtil.getFiles(inputPath);
        for (int i = 0; i < files.size(); i++) {
            File currentFile = files.get(i);
            String tempPdfFolder = outputPath;
            Path tempPdfFolderPath = Paths.get(tempPdfFolder);
            if (!Files.exists(tempPdfFolderPath) && !Files.isDirectory(tempPdfFolderPath)) {
                try {
                    Files.createDirectories(tempPdfFolderPath);
                } catch (IOException e) {
                    log.error("生成临时文件夹失败");
                }
            }
            String suffix = FileUtil.getFileExt(currentFile.getName()).toLowerCase();
            FileHandler invokeStrategy = FileHandlerFactory.getInvokeStrategy(suffix);
            List<String> imgs = invokeStrategy.handleFile(currentFile.getAbsolutePath(), outputPath);
            imgPathList.addAll(imgs);
        }
        System.out.println(imgPathList);

    }

    /**
     * 将图片列表转换为pdf文件  华泰案例
     * @throws IOException
     */
    @Test
    public void imgs2pdf() throws IOException {
        String inputPath = "E:\\文档\\工作\\致宇\\华泰\\样本\\图片";
        String outputPath = "E:\\文档\\工作\\致宇\\华泰\\样本\\pdf";
        List<String> imgPathList = new ArrayList<>();
        List<File> fileFloders = FileUtil.getfilefloders(inputPath);
        for(File fileFloder : fileFloders) {
            List<File> files = FileUtil.getFiles(fileFloder.getAbsolutePath());
            imgPathList = files.stream().map(file -> file.getAbsolutePath()).collect(Collectors.toList());
            Collections.sort(imgPathList, new Comparator<String>() {
                @Override
                public int compare(String s1, String s2) {
                    String fileNameNoExtName1 = FileUtil.getFileNameNoExtName(s1);
                    String fileNameNoExtName2 = FileUtil.getFileNameNoExtName(s2);
                    return Integer.compare(Integer.parseInt(fileNameNoExtName1),Integer.parseInt(fileNameNoExtName2)); // 按数字比较大小
                }
            });
            String fileName = fileFloder.getName();
            PdfUtil.imgList2Pdf(imgPathList,outputPath,fileName);
        }
    }

    @Test
    public void pdfs2pdf() throws FileNotFoundException {
        String inputPath = "E:\\文档\\工作\\文件测试\\ceshi";
        String outputPath = "E:\\文档\\工作\\文件测试\\ceshi";
        List<File> files = FileUtil.getFiles(inputPath);
        PdfUtil.mergerPDF(files,outputPath,"ceshi");


    }


}
